package com.monster.admin.user.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.monster.admin.user.domain.convert.UserConvert;
import com.monster.admin.user.domain.service.SysUserAuthService;
import com.monster.admin.user.domain.vo.LoginVo;
import com.monster.admin.user.infrastructure.dao.SysUserAuthDao;
import com.monster.admin.user.infrastructure.dao.SysUserDao;
import com.monster.admin.user.infrastructure.entity.SysUser;
import com.monster.admin.user.infrastructure.entity.SysUserAuth;
import com.monster.utils.StringUtils;
import com.monster.valid.annotation.ValidMonster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户授权service实现
 *
 * @author kuang
 */
@Service
public class SysUserAuthServiceImpl implements SysUserAuthService {
    /**
     * 用户dao
     */
    @Autowired
    private SysUserDao userDao;
    /**
     * 用户授权dao
     */
    @Autowired
    private SysUserAuthDao authDao;
    /**
     * 数据转换
     */
    @Autowired
    private UserConvert userConvert;

    /**
     * 通过用户名查询用户密码以及状态
     * 用户登录
     *
     * @param userName 用户名称
     * @return 用户密码以及状态信息
     */
    @Override
    public LoginVo login(@ValidMonster(isNull = false) String userName) {
        LoginVo loginVo = null;
        // 查询用户密码
        LambdaQueryWrapper<SysUserAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserAuth::getUserName, userName).
                select(SysUserAuth::getUserCode,
                        SysUserAuth::getPassword);
        SysUserAuth auth = authDao.getOne(wrapper);
        if (auth == null || StringUtils.isEmpty(auth.getPassword())) {
            return null;
        }
        // 查询用户状态以及基本信息
        LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(SysUser::getCode, auth.getUserCode()).
                select(SysUser::getName,
                        SysUser::getPetName,
                        SysUser::getSignature,
                        SysUser::isAccountNonExpired,
                        SysUser::isAccountNonLocked,
                        SysUser::isCredentialsNonExpired,
                        SysUser::isEnabled);
        SysUser user = userDao.getOne(userWrapper);
        // 数据组装
        loginVo = userConvert.toLoginVo(user, auth);
        loginVo.setUserName(userName);
        loginVo.setCode(auth.getUserCode());
        return loginVo;
    }
}
